package org.su.webadapter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.su.generalmvc.core.*;
import org.su.generalmvc.util.Assert;
import org.su.webadapter.webimpl.ServiceContext;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * Created by yangchuan on 16/1/3.
 */
@Deprecated
public class SuWebDispather extends HttpServlet {


    private IXsshApplicationContext xsshContext = null;

    protected final Log logger = LogFactory.getLog(getClass());

    /* The FilterConfig of this filter */
    private ServletConfig servletConfig;

    private ServletContext servletContext;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /**
         * 类型强制转换，尽量少用，会有一定性能影响。
         */
        String path = getUrl(request, response);
        ActionProxy ap = xsshContext.getAllActions().get(path)  ;

        if (ap != null || (ap = xsshContext.getGetActions().get(path)) != null) {
            new DefaultActionInvocation(ap, request, response)
                    .parseRequest();
        } else {
            super.doGet(request, response);
        };
    }

    @Override
    public void destroy() {
        super.destroy();
        if (!xsshContext.isSpringContext()) {
            LifeCycleManager.getInstence().destroy();
        }

        xsshContext.destroy();
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        super.init(servletConfig);
        try {

            if (xsshContext == null) {
                Assert.notNull(servletConfig, "ServletConfig must not be null");
                if (logger.isDebugEnabled()) {
                    logger.debug("Initializing filter '"
                            + servletConfig.getServletName() + "'");
                }

                this.servletConfig = servletConfig;
                InitialContext.getInstance().init(servletConfig.getInitParameter("mvc-config"),getServiceContext());
                xsshContext = InitialContext.getInstance().getContext();
            }

        } catch (Exception e) {
            throw new ServletException(e);
        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("########doPost start#########");
        /**
         * 类型强制转换，尽量少用，会有一定性能影响。
         */
        String path = getUrl(request, response);
        System.out.println("########doPost start #########:"+path);
        ActionProxy ap = xsshContext.getAllActions().get(path);

        if (ap != null || (ap = xsshContext.getPostActions().get(path)) != null) {
            new DefaultActionInvocation(ap, request, response)
                    .parseRequest();
        } else {
           super.doPost(request, response);
        }
    }

    private String getUrl(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding(xsshContext.getConfig().getEncoding());
        response.setContentType("text/html; charset="
                + xsshContext.getConfig().getEncoding());
        response.setHeader("Access-Control-Allow-Origin", "*");

        String path = request.getRequestURI();
        String sc = request.getContextPath();
        int length = path.indexOf(';');
        if(length>0){
            path = path.substring(sc.length(),path.indexOf(";"));
        }else{
            path = path.substring(sc.length());
        }
        return path;
    }

    private final ServiceContext getServiceContext() {
        this.servletContext = (this.servletConfig != null ? this.servletConfig
                .getServletContext() : this.servletContext);
        return new ServiceContext(servletContext);
    }
}
